import { useState, useEffect, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { useRequest } from 'umi';
import {
  Button,
  Descriptions,
  Result,
  Avatar,
  Space,
  Statistic,
  Modal,
  Form,
  Input,
  Select,
  message,
  Breadcrumb,
} from 'antd';
import ProTable from '@ant-design/pro-table';
import {
  MinusCircleOutlined,
  PlusOutlined,
  EditOutlined,
  CloseCircleOutlined,
  UserOutlined,
  BarChartOutlined,
  StockOutlined,
} from '@ant-design/icons';

import {
  ModalForm,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { ActionType } from '@ant-design/pro-table';

const { Option } = Select;

export default () => {
  const [rowData, setRowData] = useState({});
  const [editVisible, setEditVisible] = useState(false);
  const [addVisible, setAddVisible] = useState(false);
  const [directionList, setDirectionList] = useState([]);
  const [form] = Form.useForm();

  const ref = useRef<ActionType>();

  //获取所有团队
  const findAllGroup = useRequest((data = null) => {
    return {
      url: 'http://10.1.40.84:9993/group/findAllGroup',
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data,
    };
  });

  const findAllPeople = useRequest(
    (
      data = {
        groupType: '1',
        groupId: '',
      },
    ) => {
      return {
        url: 'http://10.1.40.84:9993/common/getGroupNumber',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );
  const insertGroup = useRequest(
    (data = null) => {
      return {
        url: 'http://10.1.40.84:9993/group/insertGroup',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
      onSuccess: () => {
        findAllGroup.run();
      },
    },
  );

  const updateGroup = useRequest(
    (data = null) => {
      return {
        url: 'http://10.1.40.84:9993/group/updateGroup',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
      onSuccess: () => {
        findAllGroup.run();
      },
    },
  );

  const getGroupLabel = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/group/getGroupLabel',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  const getDirectionLabel = useRequest((data = {}) => {
    return {
      url: 'http://10.1.40.84:9993/direction/getDirectionLabel',
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data,
    };
  });

  //修改后
  const columns: any = [
    {
      title: '子方向',
      align: 'center',
      dataIndex: 'groupName',
      key: 'groupName',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '研究方向',
      align: 'center',
      dataIndex: 'directionId',
      key: 'directionId',
      // copyable: true,
      hideInSearch: true,
      valueType: 'select',
      request: async () => {
        return getDirectionLabel.data;
      },
    },
    {
      title: '子方向负责人',
      align: 'center',
      dataIndex: 'groupControllers',
      key: 'groupControllers',
      hideInSearch: true,
      valueType: 'select',
      request: async () => {
        const personInfo = JSON.parse(
          localStorage.getItem('personInfo') || '{}',
        );
        return (
          personInfo.ROLE_管理员?.data ||
          personInfo.ROLE_方向负责人?.data ||
          personInfo.ROLE_子方向负责人?.data
        );
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      align: 'center',
      render: (text: any, record: any, _: any, action: any) => [
        <ModalForm
          title={
            <>
              <EditOutlined />
              <strong>{' 编辑子方向'}</strong>
            </>
          }
          trigger={
            <Button
              type="link"
              key="edit"
              icon={<EditOutlined />}
              onClick={() => {
                console.log(record);
              }}
            >
              编辑
            </Button>
          }
          // modalProps={{
          //   destroyOnClose: true,
          // }}
          request={async () => {
            findAllPeople.run({
              groupType: '1',
              groupId: record.id,
            });
            return record;
          }}
          onFinish={async (values) => {
            console.log(values);

            let groupControllersTemp: any = [];
            values?.groupControllers?.map((item: any) => {
              groupControllersTemp.push(item.value);
            });
            console.log(groupControllersTemp);

            await updateGroup.run({ ...values }).then((data) => {
              data ? message.success('修改成功') : message.error('修改失败');
            });
            return true;
          }}
          initialValues={record}
        >
          <ProFormText name={'id'} hidden />
          <ProFormText
            label={'子方向'}
            name={'groupName'}
            rules={[{ required: true, message: '请输入研究方向' }]}
          />
          <ProFormSelect
            label={'研究方向'}
            name={'directionId'}
            options={getDirectionLabel.data}
          />
          <ProFormSelect.SearchSelect
            name="groupControllers"
            fieldProps={{ labelInValue: false }}
            label="子方向负责人"
            mode="multiple"
            options={findAllPeople?.data}
            colProps={{ span: 6 }}
          />
        </ModalForm>,
      ],
    },
  ];

  return (
    <PageContainer
      header={{
        title: ' ',
        breadcrumb: (
          <Breadcrumb>
            <Breadcrumb.Item>系统管理</Breadcrumb.Item>
            <Breadcrumb.Item>子方向管理</Breadcrumb.Item>
          </Breadcrumb>
        ),
      }}
    >
      <ProTable
        columns={columns}
        dataSource={findAllGroup.data || []}
        request={async () => {
          var tableData: any = [];
          await findAllGroup.run().then((data) => {
            tableData = data || tableData;
          });
          return {
            data: tableData,
            success: true,
          };
        }}
        search={false}
        rowKey={'id'}
        toolbar={{}}
        toolBarRender={() => [
          <ModalForm
            title={
              <>
                <PlusOutlined />
                <strong>{' 添加子方向'}</strong>
              </>
            }
            trigger={
              <Button type={'primary'} icon={<PlusOutlined />}>
                添加子方向
              </Button>
            }
            modalProps={{
              destroyOnClose: true,
            }}
            onFinish={async (values) => {
              console.log(values);
              await insertGroup.run(values).then((data) => {
                data ? message.success('添加成功') : message.error('添加失败');
              });
              return true;
            }}
          >
            <ProFormText
              label={'团队名称'}
              name={'groupName'}
              rules={[{ required: true, message: '请输入研究方向' }]}
            />
            <ProFormSelect
              label={'研究方向'}
              name={'directionId'}
              options={getDirectionLabel.data}
              rules={[{ required: true, message: '请选择研究方向' }]}
            />
            {/* <ProFormSelect.SearchSelect
              name="groupControllers"
              label="方向负责人"
              mode="multiple"
              options={findAllPeople?.data}
              colProps={{ span: 6 }}
            /> */}
          </ModalForm>,
        ]}
      />
    </PageContainer>
  );
};
